import { ref } from "vue";
import { defineStore } from "pinia";
import router from "@router";
import type { IUserInfo } from "@interface/user";
import { getInfo } from "@api/user";

export const useUserInfoStore = defineStore(
  "userInfo",
  () => {
    // 用户信息
    let userInfo = ref<Partial<IUserInfo>>({});
    // 用户token
    let token = ref<string>("");
    // 是否登录
    let loginState = ref<boolean>(false);

    const setInfo = (data: IUserInfo) => {
      userInfo.value = data;
    };
    const getUserInfo = async () => {
      const res = await getInfo();
      if (res.code != 0) return;
      setInfo(res.data);
    };

    const setToken = (userToken: string) => {
      token.value = userToken;
      loginState.value = true;
    };

    // 退出登录
    const outLogin = () => {
      userInfo.value = {};
      token.value = "";
      loginState.value = false;
      router.replace({ path: "/" });
    };

    return {
      userInfo,
      token,
      loginState,
      setInfo,
      getUserInfo,
      setToken,
      outLogin,
    };
  },
  { persist: true }
);
